package com.tj.jinzao.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.netease.nim.uikit.business.session.constant.Extras;
import com.netease.nim.uikit.impl.NimUIKitImpl;
import com.tj.jinzao.App;
import com.tj.jinzao.R;
import com.tj.jinzao.activity.ChatActivity;
import com.tj.jinzao.activity.CityActivity;
import com.tj.jinzao.activity.FaceDetectDemoActivity;
import com.tj.jinzao.activity.FaceDetectingActivity;
import com.tj.jinzao.activity.RecentActivity;
import com.tj.jinzao.activity.SearchActivity;
import com.tj.jinzao.activity.SignActivity;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BaseFragment;
import com.tj.jinzao.callback.IMainView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.common.Settings;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.Article;
import com.tj.jinzao.model.FamilyMember;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.model.User;
import com.tj.jinzao.presenter.HealthReportPresenter;
import com.tj.jinzao.presenter.MainPresenter;
import com.tj.jinzao.utils.DisplayUtil;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.utils.Utils;
import com.tj.jinzao.widgets.ChoosePeopleDialog;
import com.tj.jinzao.widgets.HealthProgressBar;
import com.tj.jinzao.widgets.MoveLayout;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 社区文章列表
 * Created by wjy on 2019/1/1.
 */
public class MainFragment extends BaseFragment<MainPresenter> implements IMainView<List<Article>>, MoveLayout.OnMoveListener{

    @BindView(R.id.move_layout)
    MoveLayout mMoveLayout;
    @BindView(R.id.viewPager)
    ViewPager mViewPaper;
    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.ll_detect_layout)
    View mDetectLayout;
    @BindView(R.id.ll_item_layout)
    View mShowItemLayout;
    @BindView(R.id.bg_view)
    View mBgView;
    @BindView(R.id.iv_guide)
    View mGuideView;
    @BindView(R.id.tv_city)
    TextView mCityView;
    @BindView(R.id.rl_tab_layout)
    View mTabRlLayout;
    @BindView(R.id.progress_scan)
    HealthProgressBar mProgressBar;
    @BindView(R.id.fl_content_layout)
    View mContentLayout;
    @BindView(R.id.iv_tab_1)
    View iv_tab_1;
    @BindView(R.id.iv_tab_2)
    View iv_tab_2;
    @BindView(R.id.ll_chat_layout)
    View ll_chat_layout;
    @BindView(R.id.iv_tab_3)
    View iv_tab_3;
    @BindView(R.id.iv_tab_4)
    View iv_tab_4;


    private FragmentPagerAdapter mPagerAdapter;
    private int mPrevPosition = -1;
    private Fragment mCurrentFragment;
    private int mPosition = 1;
    private ChoosePeopleDialog mDialog;

    public static MainFragment newInstance() {
        MainFragment fragment = new MainFragment();
        if (fragment != null) {
            Bundle args = new Bundle(1);
            args.putInt(ARG_LAYOUT_RES_ID, R.layout.fragment_main);
            fragment.setArguments(args);
        }
        return fragment;
    }

    @Override
    public void onRequestNoData(String message) {
    }

    @Override
    public void onRequestError(String error_message) {

    }

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter(this);
    }
   private User mUser;
    @Override
    protected void setupViews(LayoutInflater inflater, View view) {
        mUser = UserManager.getInstance().getUser();
        mShowItemLayout.setAlpha(0);
        mBgView.setAlpha(0);
        mTabRlLayout.setAlpha(0);
        mViewPaper.setAlpha(0);
        mPresenter.getCityByLocation(mContext);
        mMoveLayout.setHideY((int) (0 * Constant.SCALE_Y));
        mMoveLayout.setMoveListener(this);
        mMoveLayout.setLocation(Constant.SCREEN_HEIGHT - Utils.dpToPx(150, getResources()) );
        mViewPaper.setLayoutParams(new LinearLayout.LayoutParams(
                Constant.SCREEN_WIDTH, Constant.SCREEN_HEIGHT - Utils.dpToPx(180, getResources())));
        iv_tab_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mShowItemLayout.getAlpha()>0.5){
                    ToastUtils.showToast(getActivity(),"敬请期待");
                }
            }
        });
        iv_tab_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mShowItemLayout.getAlpha()>0.5){
                    ToastUtils.showToast(getActivity(),"敬请期待");
                }

            }
        });
        setAdapter();
    }

    public void setAdapter() {
        mPagerAdapter = new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(final int position) {
                return ArticleListFragment.newInstance(position);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 0:
                        return "关注";
                    case 1:
                        return "推荐";
                    case 2:
                        return "热点";
                    case 3:
                        return "视频";
                    default:
                        return "";
                }
            }

            @Override
            public int getCount() {
                return 4;
            }


            @Override
            public void setPrimaryItem(ViewGroup container, int position, Object object) {
                super.setPrimaryItem(container, position, object);
                if (object == null || (mPrevPosition == position && mCurrentFragment != null))
                    return;
                mPrevPosition = position;
                mCurrentFragment = (Fragment) object;
                if (null == mCurrentFragment) return;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
                getChildFragmentManager().beginTransaction()
                        .remove((Fragment) object).commitAllowingStateLoss();
                try {
                    Field parentFragment = Fragment.class.getDeclaredField("mParentFragment");
                    parentFragment.setAccessible(true);
                    parentFragment.set(object, null);
                } catch (NoSuchFieldException ignored) {
                } catch (IllegalAccessException ignored) {
                }
            }
        };
        mViewPaper.setAdapter(mPagerAdapter);
        mViewPaper.setCurrentItem(mPosition);
        mTabLayout.setupWithViewPager(mViewPaper);

        View view1= LayoutInflater.from(getActivity()).inflate(R.layout.item_person_article,null);
        TextView txt1=view1.findViewById(R.id.txt);
        txt1.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtil.dip2px(getActivity(),14));
        txt1.setText("关注");
        txt1.setTextColor(getResources().getColor(R.color.global_set));
        View view2= LayoutInflater.from(getActivity()).inflate(R.layout.item_person_article,null);
        TextView txt2=view2.findViewById(R.id.txt);
        txt2.setText("推荐");
        txt2.setTextColor(getResources().getColor(R.color.global_set));
        txt2.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtil.dip2px(getActivity(),14));
        View view3= LayoutInflater.from(getActivity()).inflate(R.layout.item_person_article,null);
        TextView txt3=view3.findViewById(R.id.txt);
        txt3.setTextColor(getResources().getColor(R.color.global_set));
        txt3.setText("热点");
        txt3.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtil.dip2px(getActivity(),14));
        View view4= LayoutInflater.from(getActivity()).inflate(R.layout.item_person_article,null);
        TextView txt4=view4.findViewById(R.id.txt);
        txt4.setTextColor(getResources().getColor(R.color.global_set));
        txt4.setText("视频");
        txt4.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtil.dip2px(getActivity(),14));
        mTabLayout.getTabAt(0).setCustomView(view1);
        mTabLayout.getTabAt(1).setCustomView(view2);
        mTabLayout.getTabAt(2).setCustomView(view3);
        mTabLayout.getTabAt(3).setCustomView(view4);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    // 权限被用户同意。
                    // 执形我们想要的操作
                    mPresenter.getCityByLocation(mContext);
                }
            }
            break;
            case 2: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startDetect();
                }
            }
            break;
            case 3: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    chat();
                }
            }
        }
    }

    @Override
    public void onRequestSuccess(List<Article> Articles) {
    }

    @OnClick({R.id.ll_chat_layout})
    public void chat() {
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            User currentUser = UserManager.getInstance().getUser();
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                if(currentUser==null||currentUser.getCounselor()==null){
                    ToastUtils.showToast(getActivity(),"抱歉，您暂时无法进行专家咨询");
                }else if(currentUser!=null&&currentUser.getType()!=null&&currentUser.getType().equals("2")){
                    Intent to=new Intent();
                    to.setClass(getActivity(),RecentActivity.class);
                    startActivity(to);
                }else {
                    if(currentUser==null||currentUser.getCounselorYunxinAccount()==null){
                        ToastUtils.showToast(getActivity(),"未找到咨询师");
                        return;
                    }
                    Intent intent = new Intent();
                    intent.putExtra(Extras.EXTRA_ACCOUNT, currentUser.getCounselorYunxinAccount());
                    intent.putExtra(Extras.EXTRA_CUSTOMIZATION, NimUIKitImpl.commonP2PSessionCustomization);
                    intent.setClass(mContext, ChatActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
//
//                    NimUIKit.startP2PSession(getActivity(), currentUser.getCounselor(), null);
                }
            } else {
                ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
            }

        } else {
            ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
        }
    }
    @OnClick({ R.id.iv_tab_3})
    public void chatTab() {
        if(!canScroolTop){
            return;
        }
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            User currentUser = UserManager.getInstance().getUser();
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                if(mShowItemLayout.getAlpha()<0.5){
                    return;
                }
                if(currentUser==null||currentUser.getCounselor()==null){
                    ToastUtils.showToast(getActivity(),"抱歉，您暂时无法进行专家咨询");
                }else if(currentUser!=null&&currentUser.getType()!=null&&currentUser.getType().equals("2")){
                    Intent to=new Intent();
                    to.setClass(getActivity(),RecentActivity.class);
                    startActivity(to);
                }else {
                    if(currentUser==null||currentUser.getCounselorYunxinAccount()==null){
                        ToastUtils.showToast(getActivity(),"未找到咨询师");
                        return;
                    }
                    Intent intent = new Intent();
                    intent.putExtra(Extras.EXTRA_ACCOUNT, currentUser.getCounselorYunxinAccount());
                    intent.putExtra(Extras.EXTRA_CUSTOMIZATION, NimUIKitImpl.commonP2PSessionCustomization);
                    intent.setClass(mContext, ChatActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
//
//                    NimUIKit.startP2PSession(getActivity(), currentUser.getCounselor(), null);
                }
            } else {
                ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
            }

        } else {
            ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 3);
        }
    }

    @OnClick({R.id.iv_tab_4})
    public void detectTab() {
        if(!canScroolTop){
            return;
        }
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            if(mShowItemLayout.getAlpha()<0.5){
                return;
            }
            startDetect();
        } else {
            ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
        }
    }
    @OnClick({R.id.progress_scan})
    public void detect() {

        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            startDetect();
        } else {
            ActivityCompat.requestPermissions(mContext, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
        }
    }

    @OnClick(R.id.sign_img)
    public void sign(){
        startActivity(new Intent(mContext, SignActivity.class));
    }

    @OnClick(R.id.eat_lay)
    public void eat(){
        ToastUtils.showToast(getActivity(),"敬请期待");

    }

    @OnClick(R.id.food_lay)
    public void food(){
        ToastUtils.showToast(getActivity(),"敬请期待");
    }
    @OnClick(R.id.lay_content_top)
    public void contentTop(){
        ToastUtils.showToast(getActivity(),"敬请期待");
    }

    @OnClick({R.id.tv_city})
    public void chooseCity() {
        if(mShowItemLayout.getAlpha()>0.5){
            startActivity(new Intent(mContext, CityActivity.class));
        }
    }

    @OnClick({R.id.iv_search})
    public void search() {
        if(mShowItemLayout.getAlpha()>0.5){
            startActivity(new Intent(mContext, SearchActivity.class));
        }

    }

    private void startDetect() {
        getJc();

    }
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    private CompositeSubscription mCompositeSubscription;


    public void detachView() {
        onUnsubscribe();
    }


    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    private void getJc(){
        HashMap<String,Object> hashMap=new HashMap<>();
        hashMap.put("uid", UserManager.getInstance().getUser().getId());
        addSubscription(mApiService.getJC(hashMap), new SubscriberCallBack<String>(getActivity()) {
            @Override
            protected void onSuccess(String list) {
                if(list.equals("true")){
                    mPresenter.getFamilyList();
                }else {
                    if(list!=null&&!list.equals("")){
                        ToastUtils.showToast(getActivity(),list);
                    }else {
                        ToastUtils.showToast(getActivity(),"尚未获取检测权限");
                    }

                }

            }

            @Override
            protected void onFailure(ResultResponse response) {
                ToastUtils.showToast(getActivity(),"检测权限获取失败");

            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
            }
        });

    }

    @Override
    public void onLocation(String city) {
//        if(city!=null&&!city.equals("")){
//            mCityView.setText(city);
//        }else {
            mCityView.setText("全国城市");
//        }


    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(mPresenter!=null){
            //同步用户信息（咨询师分配功能）
            if(mUser==null){
                mUser = UserManager.getInstance().getUser();
            }
            mPresenter.getPersonData(mUser.getId());
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        if(App.sCity != null){
            mCityView.setText(App.sCity.getName());
        }
        if(mUser!=null){
            //同步用户信息（咨询师分配功能）
            mPresenter.getPersonData(mUser.getId());
        }

    }

    @Override
    public void getFamily(List<FamilyMember> list) {
        mDialog = new ChoosePeopleDialog.Builder(mContext).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getId() == R.id.btn_confirm) {
                    String name = (String) view.getTag();
                    mPresenter.addFamily(name);
                    mDialog.dismiss();
                } else {
                    int id = 0;
                    try {
                        id = (Integer) view.getTag(R.id.data);
                    } catch (Exception e) {
                    }
                    Settings.setLong(mContext, Settings.KEY_PREF_FAMILY_ID, id);
                    Intent intent = new Intent(mContext, FaceDetectDemoActivity.class);
                    startActivity(intent);
                }
                mDialog.dismiss();
            }
        }).setFamilyList(list).create();
        mDialog.show();
    }

    @Override
    public void addFamily(FamilyMember member) {
        Settings.setLong(mContext, Settings.KEY_PREF_FAMILY_ID, member.getId());
        Intent intent = new Intent(mContext, FaceDetectDemoActivity.class);
        startActivity(intent);
    }

    @Override
    public void onUserInfoSuccess(User user) {
        if(user!=null){
            UserManager.saveUserData(user);
        }


    }

    @Override
    public void onUserInfoFailed(ResultResponse response) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        detachView();
        if (mProgressBar != null) mProgressBar.onDestroy();

    }
    private boolean canScroolTop=false;

    @Override
    public void onMoved(float transX, float transY) {

        Log.i("wjy","onMoved transY:" + transY);
        float alpha = ((Constant.SCREEN_HEIGHT / 2 - transY) / (Constant.SCREEN_HEIGHT / 2));
        float alpha1 = ((Constant.SCREEN_HEIGHT * 3 / 5 - transY) / (Constant.SCREEN_HEIGHT / 2.5f));
        if(transY>200){
            canScroolTop=false;
        }else if(transY<60){
            canScroolTop=true;
        }
        mDetectLayout.setAlpha(1 - alpha);
        mGuideView.setAlpha(1 - alpha);
        mShowItemLayout.setAlpha(alpha);
        mBgView.setAlpha(alpha);
        mTabRlLayout.setAlpha(alpha1);
        mViewPaper.setAlpha(alpha1);
    }

    @Override
    public void onStart() {
        super.onStart();
        mTabLayout.post(new Runnable() {
            @Override
            public void run() {
                setIndicator(mTabLayout, 10, 10);
            }
        });
    }

    public static void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

}
